<template>
  <div v-if="visible" class="context-menu" :style="{left: x + 'px', top: y + 'px'}" @mousedown.stop>
    <ul>
      <li v-for="(item, idx) in menu" :key="item.label" class="menu-li"
          @mouseenter="hoverIndex = idx" @mouseleave="hoverIndex = null">
        <div class="menu-item" @click.stop="onItemClick(item)">
          <span v-if="item.icon" class="icon"><img :src="item.icon" /></span>
          <span>{{ item.label }}</span>
          <span v-if="item.children" class="arrow">▶</span>
        </div>
        <div v-if="item.children && hoverIndex === idx" class="submenu">
          <ul>
            <li v-for="sub in item.children" :key="sub.label" @click.stop="onSubMenuClick(sub)">
              <span v-if="sub.icon" class="icon"><img :src="sub.icon" /></span>
              <span>{{ sub.label }}</span>
            </li>
          </ul>
        </div>
      </li>
    </ul>
  </div>
</template>

<script setup>
import { ref, watch, onMounted, onBeforeUnmount } from 'vue'
const props = defineProps({
  visible: Boolean,
  x: Number,
  y: Number,
  menu: Array
})
const emit = defineEmits(['select', 'close'])
const hoverIndex = ref(null)
function onItemClick(item) {
  console.log('onItemClick', item)
  if (item.disabled) return
  emit('select', item)
  emit('close')
}
function onSubMenuClick(sub) {
  console.log('onSubMenuClick', sub)
  if (sub.disabled) return
  emit('select', sub)
  emit('close')
}
function onBodyClick() { emit('close') }
onMounted(() => { document.body.addEventListener('mousedown', onBodyClick) })
onBeforeUnmount(() => { document.body.removeEventListener('mousedown', onBodyClick) })
watch(() => props.visible, v => { if (!v) hoverIndex.value = null })
</script>

<style scoped>
.context-menu {
  position: fixed;
  z-index: 9999;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 24px #0002;
  min-width: 180px;
  font-size: 15px;
  color: #222;
  padding: 6px 0;
  user-select: none;
}
ul { list-style: none; margin: 0; padding: 0; }
.menu-li {
  position: relative;
}
.menu-item {
  display: flex; align-items: center; gap: 8px;
  padding: 6px 22px 6px 18px; cursor: pointer;
  white-space: nowrap;
}
.menu-item:hover { background: #e3eefd; }
.icon { width: 18px; height: 18px; display: inline-flex; align-items: center; }
.icon img { width: 100%; height: 100%; }
.arrow { margin-left: auto; font-size: 12px; }
.submenu {
  position: absolute;
  left: 100%;
  top: 0;
  min-width: 180px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 4px 24px #0002;
  padding: 6px 0;
  z-index: 99999;
  border: 1px solid #e3eefd;
}
.submenu ul {
  list-style: none;
  margin: 0;
  padding: 0;
}
.submenu li {
  padding: 6px 22px 6px 18px;
  cursor: pointer;
  white-space: nowrap;
}
.submenu li:hover {
  background: #e3eefd;
}
</style> 